package com.are.inventario;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;
import android.telephony.TelephonyManager;

public class ActualizarTrafoActivity extends Activity implements
		OnClickListener {

	private Uri fileUri;
	private static int SELECT_PICTURE = 2;

	private boolean sendfile = false;
	private String _path = "";

	private ProgressDialog progressDialog;
	private String ReceiveServer = "";
	private EditText codigo;
	private String tipo;
	private String key;

	private final Handler progressHandler = new Handler() {

		public void handleMessage(Message msg) {
			if (msg.obj != null) {
				ReceiveServer = (String) msg.obj;
				ShowMensaje(ReceiveServer);
			}
			progressDialog.dismiss();
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_actualizar_trafo);

		Button btnAction = (Button) findViewById(R.id.cmdBuscarImagen);
		btnAction.setOnClickListener(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_actualizar_trafo, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == SELECT_PICTURE) {
			fileUri = data.getData();
			InputStream is;
			try {
				is = getContentResolver().openInputStream(fileUri);
				BufferedInputStream bis = new BufferedInputStream(is);
				Bitmap bitmap = BitmapFactory.decodeStream(bis);
				ImageView iv = (ImageView) findViewById(R.id.imageView1);
				iv.setImageBitmap(bitmap);
				is.close();
				sendfile = true;
				_path = this.getPath(fileUri);
			} catch (FileNotFoundException e) {
				sendfile = false;
				e.printStackTrace();
			} catch (IOException e) {
				sendfile = false;
				e.printStackTrace();
			}
		}
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v.getId() == R.id.cmdBuscarImagen) {
			int code = SELECT_PICTURE;
			Intent intent = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
			startActivityForResult(intent, code);
		}

	}

	private String getPath(Uri uri) {
		String[] projection = { android.provider.MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, projection, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(android.provider.MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.menu_agregar:
			if (sendfile) { // Si se puede enviar el archivo
				System.out.print(fileUri.getPath());
				codigo = (EditText)findViewById(R.id.txtCodigo);
				key = codigo.getText().toString();
				RadioButton alta = (RadioButton)findViewById(R.id.optAlta);
				RadioButton modificar = (RadioButton)findViewById(R.id.optModificar);
				
				if (alta.isChecked()) {
					tipo = "ALTA";
				}else if (modificar.isChecked()) {
					tipo = "MODIFICACION";
				}else {
					tipo = "ELIMINACION";
				}
				SendInfo();
			} else {
				Toast toast = Toast.makeText(getApplicationContext(),
						"Imagen no se puede enviar", Toast.LENGTH_LONG);
				toast.show();
			}
			break;
		case R.id.menu_actualizar:
			break;
		}
		return true;

	}

	private void ShowMensaje(String data) {
		if (data.equals("OK")) {
			Toast toast = Toast.makeText(getApplicationContext(), data,
					Toast.LENGTH_LONG);
			toast.show();
			finish();
		} else { // error al confirmar la orden
			AlertDialog alert = (AlertDialog) this.crearDialogoAlerta(data);
			alert.show();
		}

	}

	private Dialog crearDialogoAlerta(String mensaje) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Informacion");
		builder.setMessage(mensaje);
		builder.setCancelable(false);
		builder.setPositiveButton("OK",
				new android.content.DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});
		return builder.create();
	}

	private void SendInfo() {
		try {

			File imagefile = new File(_path);
			byte[] data = new byte[(int) imagefile.length()];
			FileInputStream fis = new FileInputStream(imagefile);
			fis.read(data);

			SendFile(imagefile.getName(), data); // enviando foto

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void SendFile(final String filename, final byte bytes[]) {
		progressDialog = ProgressDialog.show(ActualizarTrafoActivity.this, "",
				"Por favor espere mientras se envian los datos...", true);

		new Thread(new Runnable() {
			public void run() {
				TelephonyManager tm = (TelephonyManager) ActualizarTrafoActivity.this
						.getSystemService(Context.TELEPHONY_SERVICE);
				String imei = tm.getDeviceId();
				SendInfoUpdateTrafo conn = new SendInfoUpdateTrafo(
						"http://siscos.fcr.com.co:8080/AreApp/SrvGetFileTrafo",
						bytes, filename);
				Message msg = progressHandler.obtainMessage();
				msg.obj = conn.Send(key, tipo, imei);
				progressHandler.sendMessage(msg);
			}
		}).start();
	}

}
